import { Battle } from '../models/Battle';
import { BattleState, Team, BattleReport, TurnResult, BattleAction } from '../types/battle';
import { General } from '../models/General';
import { BattleReporter } from './BattleReporter';
import { Formation } from '../models/Formation';

export class BattleController {
  private readonly MAX_TURNS = 8;
  private battle: Battle;
  private state: BattleState;
  private reporter: BattleReporter;

  constructor(teamA: Team, teamB: Team) {
    // 为每个队伍创建阵型实例
    const formationA = new Formation(teamA.formation);
    const formationB = new Formation(teamB.formation);

    // 使用正确的参数初始化 Battle
    this.battle = new Battle(
      teamA.generals,
      teamB.generals,
      formationA,
      formationB
    );

    this.state = {
      currentTurn: 1,
      teams: [teamA, teamB],
      actionOrder: [],
      isEnded: false
    };
    
    this.reporter = new BattleReporter();
  }

  public async startBattle(): Promise<BattleReport> {
    while (!this.state.isEnded && this.state.currentTurn <= this.MAX_TURNS) {
      const turnResult = await this.executeTurn();
      this.reporter.recordTurn(turnResult, this.state.currentTurn);

      this.checkBattleEnd();
      this.state.currentTurn++;
    }

    if (this.state.winner) {
      this.reporter.setWinner(this.state.winner);
    }
    this.reporter.recordFinalState(this.state.teams);

    return this.reporter.getReport();
  }

  private async executeTurn(): Promise<TurnResult> {
    const turnResult: TurnResult = {
      turnNumber: this.state.currentTurn,
      timestamp: Date.now(),
      actions: [],
      casualties: new Map(),
      effects: []
    };

    // 计算行动顺序
    this.calculateActionOrder();

    // 按顺序执行每个武将的行动
    for (const general of this.state.actionOrder) {
      if (!general.isAlive()) continue;

      // 处理回合开始效果
      await this.handleTurnStart(general);

      // 执行武将行动
      const actions = await this.executeGeneralAction(general);
      turnResult.actions.push(...actions);

      // 处理回合结束效果
      await this.handleTurnEnd(general);

      // 检查是否战斗结束
      if (this.checkBattleEnd()) break;
    }

    return turnResult;
  }

  private calculateActionOrder(): void {
    const allGenerals = [...this.state.teams[0].generals, ...this.state.teams[1].generals]
      .filter(general => general.isAlive());

    this.state.actionOrder = allGenerals.sort((a, b) => {
      // 首先按先攻值排序
      if (a.attributes.initiative !== b.attributes.initiative) {
        return b.attributes.initiative - a.attributes.initiative;
      }
      // 先攻值相同时按智力排序
      if (a.attributes.intelligence !== b.attributes.intelligence) {
        return b.attributes.intelligence - a.attributes.intelligence;
      }
      // 最后按武力排序
      return b.attributes.power - a.attributes.power;
    });
  }

  private async executeGeneralAction(general: General): Promise<BattleAction[]> {
    // 使用 battle 实例而不是 battleSystem
    return await general.executeAction(this.battle);
  }

  private checkBattleEnd(): boolean {
    // 检查任意一方是否所有武将都阵亡
    const teamADefeated = this.state.teams[0].generals.every(g => !g.isAlive());
    const teamBDefeated = this.state.teams[1].generals.every(g => !g.isAlive());

    if (teamADefeated || teamBDefeated) {
      this.state.isEnded = true;
      this.state.winner = teamADefeated ? this.state.teams[1] : this.state.teams[0];
      return true;
    }

    return false;
  }

  private getOpposingTeam(general: General): Team {
    return this.state.teams.find(team => 
      !team.generals.includes(general)
    )!;
  }

  private calculateFinalStats(report: BattleReport): void {
    // 计算最终统计数据
    this.state.teams.forEach(team => {
      team.generals.forEach(general => {
        report.finalState.remainingTroops.set(general.id, general.troops);
        // 其他统计数据计算...
      });
    });
  }

  private async handleTurnStart(general: General): Promise<void> {
    // 处理回合开始时的效果
    // 目前为空实现，未来可以添加状态效果检查等逻辑
  }

  private async handleTurnEnd(general: General): Promise<void> {
    // 处理回合结束时的效果
    // 目前为空实现，未来可以添加状态效果结算等逻辑
  }
}
